#ifndef CHATWIDGET_H
#define CHATWIDGET_H

#include <QWidget>
#include <QTextEdit>
#include <QLineEdit>
#include <QPushButton>
#include <QNetworkAccessManager>
#include <QNetworkReply>
#include <QBuffer>
#include "DatabaseManager.h"

class ChatWidget : public QWidget {
    Q_OBJECT
    Q_PROPERTY(bool m_isInterventionMode READ isInterventionMode)
public:
    explicit ChatWidget(QWidget *parent = nullptr);
    void setDatabaseManager(DatabaseManager *dbManager);
    void setApiKey(const QString &apiKey);
    void setApiType(const QString &type);
    bool isInterventionMode() const { return m_isInterventionMode; }
    QString getApiKey() const { return m_apiKey; }
    void setInterventionApiKey(const QString &apiKey) { m_interventionApiKey = apiKey; }

signals:
    void userQuestionAsked(const QString &question);
    void switchToInterventionModule(); // 新增：切换到智能干预模块的信号

public slots:
    void testApiConnection();

private slots:
    void onSendClicked();
    void onReplyFinished();
    void onReadyRead(); // 处理数据流
    void onSwitchToInterventionClicked(); // 新增：处理切换按钮点击

private:
    QTextEdit *m_chatHistory;
    QLineEdit *m_input;
    QPushButton *m_sendButton;
    QPushButton *m_switchToInterventionButton; // 新增：切换到智能干预模块的按钮
    QNetworkAccessManager *m_networkManager;
    QString m_apiKey;
    QString m_apiType;
    DatabaseManager *m_dbManager;
    QVector<QPair<QString, QString>> m_conversationHistory;
    QNetworkReply *m_currentReply; // 当前响应
    QString m_currentAnswer; // 当前累积的回答
    bool m_isInterventionMode; // 跟踪当前是否处于智能干预模式
    QString m_dialogApiKey; // 存储对话模式的API密钥
    QString m_interventionApiKey; // 存储干预模式的API密钥

    QNetworkRequest createApiRequest();
    QByteArray createRequestBody();
    QString parseApiResponse(const QByteArray &response);
    QString parseSSEResponse(const QByteArray &response); // 解析SSE格式
};

#endif // CHATWIDGET_H
